package P1线性结构;
//用栈实现队列的问题
public class StackToQueue {
    public static void main(String[] args) {
        QueueImplByStack<Integer> q = new QueueImplByStack<>();
        System.out.println(q);
        q.offer(1);
        q.offer(2);
        q.offer(3);
        System.out.println(q);
        System.out.println(q.poll());
        System.out.println(q);
        q.offer(4);
        System.out.println(q);
    }
}
class QueueImplByStack<E> implements Queue<E>{
    private ArrayStack<E> stackA;
    private ArrayStack<E> stackB;

    public QueueImplByStack() {
        stackA = new ArrayStack<>();
        stackB = new ArrayStack<>();
    }

    @Override
    public void offer(E element) {
        stackA.push(element);
    }

    @Override
    public E poll() {
        while (!stackA.isEmpty()) {
            stackB.push(stackA.pop());
        }
        E ret = stackB.pop();
        while (!stackB.isEmpty()) {
            stackA.push(stackB.pop());
        }
        return ret;
    }

    @Override
    public E element() {
        while (!stackA.isEmpty()) {
            stackB.push(stackA.pop());
        }
        E ret = stackB.peek();
        while (!stackB.isEmpty()) {
            stackA.push(stackB.pop());
        }
        return ret;
    }

    @Override
    public int size() {
        return stackA.size();
    }

    @Override
    public boolean isEmpty() {
        return stackA.isEmpty();
    }

    @Override
    public void clear() {
        stackA.clear();
    }

    @Override
    public String toString() {
        return stackA.toString();
    }
}

